package com.mxx.bu_yang.activity.off_line;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mxx.basic.server.RetrofitHelper;
import com.mxx.basic.server.enums.RequestEnum;
import com.mxx.basic.server.retrofit.observer.StringObserver;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.bu_yang.R;
import com.mxx.bu_yang.ScannerService;
import com.mxx.bu_yang.adapter.off_line.BarcodeResultAdapter;
import com.mxx.bu_yang.common.CommonTitleActivity;
import com.mxx.bu_yang.dialog.FriendlyHintDialog;
import com.mxx.bu_yang.dialog.ModifyBarcodeDialog;
import com.mxx.bu_yang.dialog.TemporaryPositionDialog;
import com.mxx.bu_yang.response.LoginInfoResponse;
import com.mxx.bu_yang.response.TemporaryPositionResponse;
import com.mxx.bu_yang.utils.PermissionUtil;
import com.mxx.common.config.NetUrlConfig;
import com.mxx.common.response.BaseEntityResponse;
import com.symbol.emdk.EMDKManager;
import com.symbol.emdk.EMDKResults;
import com.symbol.emdk.barcode.BarcodeManager;
import com.symbol.emdk.barcode.ScanDataCollection;
import com.symbol.emdk.barcode.ScannerConfig;
import com.symbol.emdk.barcode.ScannerException;
import com.symbol.emdk.barcode.ScannerInfo;
import com.symbol.emdk.barcode.ScannerResults;
import com.symbol.emdk.barcode.StatusData;
import com.yp.loading.widget.LoadingDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;


/**
 * @ProjectName: Bu_Yang
 * @Package: com.mxx.bu_yang.activity
 * @ClassName: BarcodeListActivity
 * @Description: java类作用描述
 * @Author: 刘江飞
 * @Version: 1.0
 */
public class BarcodeListActivity extends CommonTitleActivity implements View.OnClickListener, OnItemChildClickListener {
    private EditText edt_result;
    private RecyclerView rv_result;
    private TextView tv_submit;
    private TextWatcher textWatcher;
    private LoadingDialog mLoading;
    private BarcodeResultAdapter barcodeResultAdapter;
    private final Map<String, Object> map = new HashMap<>();
    private List<String> tempBarcodeList;
    private boolean isFirst = true;
    private final String[] permissions = {Manifest.permission.CAMERA
            , Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.READ_EXTERNAL_STORAGE};
    /**
     * menu_id 5 离线入库
     * menu_id 6 离线出库
     * menu_id 7 出库物品回退
     */
    private final String MENU_ID = "menu_id";
    private final int SCAN_CODE_OFF_IN = 5;
    private final int SCAN_CODE_OFF_OUT = 6;
    private final int SCAN_CODE_OFF_BACK = 7;

    private final String STATUS = "status";
    private static final int STATUS_READ_FILE = 0;
    private static final int STATUS_BARCODE_ADD = 1;
    private static final int STATUS_BEFORE_SUBMIT = 2;
    private static final int STATUS_AFTER_SUBMIT = 3;
    private static final int STATUS_BACK_ICON_PRESS = 4;
    private static final int STATUS_BACK_KEY_PRESS = 5;
    private static final int STATUS_FILE_CONTENT_BACK_SHOW = 6;
    private static final int STATUS_BARCODE_DELETE = 7;
    private static final int STATUS_BARCODE_UPDATE = 8;
    private static final int STATUS_OPEN_ONETIME_CREATE_ONETIME = 9;
    private static final String BARCODE = "barcode";
    private static final String BARCODE_NEW = "barcode_new";


    //提交离线入库，离线出库，出库物品回退前会创建一个保存条码的文件
    //该文件生成一个文件名，提交请求成功后使用该文件名
    private static final String FILE_NAME = "file_name";
    //保存当天所有条码的文件
    private static final String TEMPORARY_FILE = "temporary_file";

    private final Handler mHandler = new Handler();
    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mHandler.removeCallbacks(mRunnable);
            int menu_id = (int) map.get(MENU_ID);
            submitByMenuId(menu_id);
        }
    };

    private void submitByMenuId(int menu_id) {
        if (menu_id != SCAN_CODE_OFF_IN
                && menu_id != SCAN_CODE_OFF_OUT
                && menu_id != SCAN_CODE_OFF_BACK) {
            ToastUtils.showToast(this, "目标路径未找到");
            return;
        }
        String requestUrl = getRequestUrl(menu_id);
        List<String> list = barcodeResultAdapter.getData();
        String submit_content = listToString(list);
        if (menu_id == SCAN_CODE_OFF_IN || menu_id == SCAN_CODE_OFF_OUT) {
            offlineWarehouseInOrWarehouseOut(requestUrl, submit_content);
        }
        if (menu_id == SCAN_CODE_OFF_BACK) {
            warehouseInBack(requestUrl, submit_content);
        }
    }

    private String getRequestUrl(int menu_id) {
        String url = "";
        if (menu_id == SCAN_CODE_OFF_IN) {
            url = "user/operationReceipt/offlineSubmit";
        }
        if (menu_id == SCAN_CODE_OFF_OUT) {
            url = "user/operationReceipt/offlineOut";
        }
        if (menu_id == SCAN_CODE_OFF_BACK) {
            url = "user/operationReceipt/selTemporary";
        }

        return url;
    }

    private String listToString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (String response : list) {
            if (response != null) {
                if (list.indexOf(response) == 0) {
                    result = new StringBuilder(response);
                } else {
                    result.append(",").append(response);
                }
            }
        }
        return result.toString();
    }

    private void offlineWarehouseInOrWarehouseOut(String requestUrl, String content) {
        Map<String, Object> params = getParams(content);
        String json = new Gson().toJson(params);
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL)
                .appendUrl(requestUrl)
                .addParams(json)
                .build()
                .observable(RequestEnum.METHOD_POST_JSON_STRING)
                .subscribe(new StringObserver(true, this) {
                    @Override
                    protected void onSuccess(String json) {
                        handleJson(json);
                    }

                    @Override
                    protected void onFailed(int code, String msg) {
                        super.onFailed(code, msg);
                        handleErrorJson(msg);
                    }
                });
    }

    private Map<String, Object> getParams(String submit_content) {
        Map<String, Object> map = new HashMap<>();
        map.put("barcode", submit_content);
        LoginInfoResponse response = getLoginInfo();
        if (response != null) {
            int userId = response.userId;
            map.put("userId", userId);
        }
        return map;
    }

    private void handleJson(String json) {
        BaseEntityResponse<Object> response = paramsJson(json);
        if (response == null) {
            return;
        }
        if (response.code == 0) {
            runOnUiThread(() -> {
                refreshUi();
                showFriendlyHintDialog(response.tip);
            });
        } else {
            handleErrorJson(response.tip);
        }
    }

    private BaseEntityResponse<Object> paramsJson(String json) {
        if (json == null || json.isEmpty()) {
            return null;
        }
        return new Gson().fromJson(json, new TypeToken<BaseEntityResponse<Object>>() {
        }.getType());
    }

    private void refreshUi() {
        resetEditText();
        barcodeResultAdapter.getData().clear();
        barcodeResultAdapter.notifyDataSetChanged();
    }

    private void showFriendlyHintDialog(String json) {
        if (json == null) {
            ToastUtils.showToast(this, "返回信息为空");
            return;
        }
        FriendlyHintDialog dialog = new FriendlyHintDialog();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("hint", json);
        dialog.setArguments(mBundle);
        dialog.show(getSupportFragmentManager(), "FriendlyHintDialog");
    }

    private void handleErrorJson(String msg) {
        runOnUiThread(() -> BarcodeListActivity.this.showFriendlyHintDialog(msg));
    }

    private void warehouseInBack(String requestUrl, String submit_content) {
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL)
                .appendUrl(requestUrl)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver(true, this) {
                    @Override
                    protected void onSuccess(String json) {
                        List<TemporaryPositionResponse> list = paramsJsonToList(json);
                        showTemporaryPositionDialog(submit_content, list);
                    }

                    @Override
                    protected void onFailed(int code, String msg) {
                        super.onFailed(code, msg);
                        ToastUtils.showToast(BarcodeListActivity.this, msg);
                    }
                });
    }

    private List<TemporaryPositionResponse> paramsJsonToList(String json) {
        BaseEntityResponse<Object> response = paramsJson(json);
        if (response == null || response.data == null) {
            ToastUtils.showToast(this, "数据为空");
            return null;
        }
        return new Gson().fromJson(new Gson().toJson(response.data), new TypeToken<List<TemporaryPositionResponse>>() {
        }.getType());
    }

    private void showTemporaryPositionDialog(String barcode, List<TemporaryPositionResponse> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        TemporaryPositionDialog dialog = new TemporaryPositionDialog();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("list", new Gson().toJson(list));
        dialog.setArguments(mBundle);
        dialog.setBackDataListener(response -> {
            String request_url = "user/operationReceipt/deliveryReturn";
            Map<String, String> params = getMapParams(barcode, response);
            goodsBack(request_url, params);
        });
        dialog.show(getSupportFragmentManager()
                , "TemporaryPositionDialog");
    }

    private Map<String, String> getMapParams(String barcode, TemporaryPositionResponse response) {
        Map<String, String> map = new HashMap<>();
        if (response == null) {
            ToastUtils.showToast(this, "仓位信息为空");
            return map;
        }
        map.put("barcode", barcode);
        map.put("storId", String.valueOf(response.wareId));
        map.put("storName", response.wareName);
        LoginInfoResponse info = getLoginInfo();
        if (info != null) {
            int userId = info.userId;
            map.put("userId", String.valueOf(userId));
        }

        return map;
    }


    private void goodsBack(String request_url, Map<String, String> query) {
        String json = new Gson().toJson(query);
        new RetrofitHelper
                .Builder()
                .baseUrl(NetUrlConfig.BASE_URL)
                .appendUrl(request_url)
                .addParams(json)
                .build()
                .observable(RequestEnum.METHOD_POST_JSON_STRING)
                .subscribe(new StringObserver(false, this) {
                    @Override
                    protected void onSuccess(String json) {
                        handleJson(json);
                        refreshUi();
                    }

                    @Override
                    protected void onFailed(int code, String msg) {
                        super.onFailed(code, msg);
                        handleErrorJson(msg);
                    }
                });
    }

    //SEUIC设备使用
    private ScanReceiver receiver;

    //zebra
    private EMDKManager emdkManagers = null;
    private BarcodeManager barcodeManager = null;
    private com.symbol.emdk.barcode.Scanner scanner = null;
    private boolean bSoftTriggerSelected = false;
    private boolean bDecoderSettingsChanged = false;
    private boolean bExtScannerDisconnected = false;
    private final Object lock = new Object();
    private com.symbol.emdk.barcode.Scanner.DataListener scannerDataListener;
    private com.symbol.emdk.barcode.Scanner.StatusListener scannerStatusListener;
    private EMDKManager.EMDKListener emdkListener;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_barcode_list;
    }

    @Override
    protected int getTitleType() {
        return TITLE_LEFT_BACK_MIDDLE_TITLE_RIGHT_TEXT;
    }


    @Override
    public void initView() {
        super.initView();
        edt_result = findViewById(R.id.edt_result);
        rv_result = findViewById(R.id.rv_result);
        tv_submit = findViewById(R.id.tv_submit);
        tv_title.setText("条形码");
        tv_right.setText("文件");

        tempBarcodeList = new ArrayList<>();
//        saveStatus(STATUS_READ_FILE);
        saveStatus(STATUS_OPEN_ONETIME_CREATE_ONETIME);

        initRecycleView();
        initParams();
        initTextWatcher();
    }

    private void saveStatus(int status) {
        if (status != STATUS_READ_FILE
                && status != STATUS_BARCODE_ADD
                && status != STATUS_BEFORE_SUBMIT
                && status != STATUS_AFTER_SUBMIT
                && status != STATUS_BACK_ICON_PRESS
                && status != STATUS_BACK_KEY_PRESS
                && status != STATUS_FILE_CONTENT_BACK_SHOW
                && status != STATUS_BARCODE_DELETE
                && status != STATUS_BARCODE_UPDATE
                && status != STATUS_OPEN_ONETIME_CREATE_ONETIME
        ) {
            return;
        }
        map.put(STATUS, status);
    }

    private void initRecycleView() {
        LinearLayoutManager mManager = new LinearLayoutManager(this);
        mManager.setOrientation(RecyclerView.VERTICAL);
        rv_result.setLayoutManager(mManager);
        if (rv_result.getItemDecorationCount() == 0) {
            RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view
                        , @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                    int mode = parent.getChildLayoutPosition(view);
                    if (mode == 0) {
                        outRect.top = 17;
                        outRect.bottom = 0;
                    } else if (mode == state.getItemCount() - 1) {
                        outRect.top = 0;
                        outRect.bottom = 17;
                    } else {
                        outRect.top = 0;
                        outRect.bottom = 0;
                    }
                }
            };
            rv_result.addItemDecoration(decoration);
        }

        barcodeResultAdapter = new BarcodeResultAdapter(R.layout.adapter_barcode_result_new);
        rv_result.setAdapter(barcodeResultAdapter);
    }

    private void initParams() {
        int menu_id = (int) getSerValueByKey("menu_id");
        map.put(MENU_ID, menu_id);
    }

    private void initTextWatcher() {
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                runOnUiThread(() -> {
//                    saveStatus(STATUS_BARCODE_ADD);
                    String barcode = s.toString();
                    saveBarcode(BARCODE, barcode);
                    resetEditText();
                    checkPermissions();
                });
            }
        };
    }

    //保存条形码
    private void saveBarcode(String key, String barcode) {
        map.put(key, barcode);
    }

    //重置输入框
    private void resetEditText() {
        edt_result.removeTextChangedListener(textWatcher);
        edt_result.setText("");
        edt_result.addTextChangedListener(textWatcher);
    }

    private void checkPermissions() {
        PermissionUtil
                .getInstance()
                .requestPermission(this, new PermissionUtil.IPermissionListener() {
                    @Override
                    public void allPermissionGranted() {
                        Log.i("TAG", "权限已经被允许");
                        int status = (int) map.get(STATUS);
                        doDifferentThingByStatus(status);
                    }

                    @Override
                    public void partPermissionRefuse() {
                        Log.i("TAG", "权限被拒绝，请手动打开权限");
                        ToastUtils.showToast(BarcodeListActivity.this, "权限被拒绝，请手动打开权限");
                    }
                }, permissions);

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().handlerActivityResult(requestCode, grantResults);
    }

    private void doDifferentThingByStatus(int status) {
        new Thread(() -> {
            runOnUiThread(() -> {
                Log.i("TAG", "加载Loading");
                showLoading();
            });
            String hint = getStatusExceptionHint(status);
            if (!hint.isEmpty()) {
                removeLoadingAndFriendlyHint(hint);
                return;
            }
            switch (status) {
                case STATUS_READ_FILE:
                    readFile();
                    break;
                case STATUS_BARCODE_ADD:
                    scanOneTimeSaveOneTime();
                    break;
                case STATUS_BEFORE_SUBMIT:
                    saveBeforeSubmit();
                    break;
                case STATUS_AFTER_SUBMIT:
                    saveAfterSubmit();
                    break;
                case STATUS_BACK_ICON_PRESS:
                    backIconPress();
                    break;
                case STATUS_BACK_KEY_PRESS:
                    backKeyPress();
                    break;
                case STATUS_FILE_CONTENT_BACK_SHOW:
                    fileContentBackShow();
                    break;
                case STATUS_BARCODE_DELETE:
                    deleteBarcode();
                    break;
                case STATUS_BARCODE_UPDATE:
                    updateBarcode();
                    break;
                case STATUS_OPEN_ONETIME_CREATE_ONETIME:
                    openOneTimeCreateOneTime();
                    break;
            }
        }).start();
    }


    private void showLoading() {
        mLoading = new LoadingDialog();
        mLoading.show(getSupportFragmentManager(), "LoadingDialog");
    }

    private String getStatusExceptionHint(int status) {
        if (status != STATUS_READ_FILE
                && status != STATUS_BARCODE_ADD
                && status != STATUS_BEFORE_SUBMIT
                && status != STATUS_AFTER_SUBMIT
                && status != STATUS_BACK_ICON_PRESS
                && status != STATUS_BACK_KEY_PRESS
                && status != STATUS_FILE_CONTENT_BACK_SHOW
                && status != STATUS_BARCODE_DELETE
                && status != STATUS_BARCODE_UPDATE) {
            return "未知的操作";
        }
        return "";
    }

    private void hideLoading() {
        if (mLoading != null) {
            new Handler().postDelayed(() -> mLoading.hideLoadingView(), 0);
        }
    }

    private void removeLoadingAndFriendlyHint(String hint) {
        runOnUiThread(() -> {
            hideLoading();
            ToastUtils.showToast(this, hint);
        });
    }

    private String getTargetFilePath(int status) {
        String path = "";
        Calendar calendar;
        String file_name;
        switch (status) {
            case STATUS_READ_FILE:
            case STATUS_BARCODE_ADD:
                calendar = Calendar.getInstance();
                file_name = millionToFormatTime(calendar.getTimeInMillis(), "yyyyMMdd")
                        + getSubmitDes(false)
                        + ".txt";
                path = getSDPath() + "/" + getDirectory() + "/" + file_name;
                map.put(TEMPORARY_FILE, path);
                break;
            case STATUS_BEFORE_SUBMIT:
                calendar = Calendar.getInstance();
                file_name = millionToFormatTime(calendar.getTimeInMillis(), "yyyyMMddHHmmss");
                map.put(FILE_NAME, file_name);
                path = getSDPath() + "/" + getDirectory() + "/" + file_name + getSubmitDes(false) + ".txt";
                break;
            case STATUS_AFTER_SUBMIT:
                file_name = (String) map.get(FILE_NAME);
                path = getSDPath() + "/" + getDirectory() + "/" + file_name + getSubmitDes(true) + ".txt";
                break;
            case STATUS_BACK_ICON_PRESS:
            case STATUS_BACK_KEY_PRESS:
                calendar = Calendar.getInstance();
                file_name = millionToFormatTime(calendar.getTimeInMillis(), "yyyyMMddHHmmss");
                path = getSDPath() + "/" + getDirectory() + "/" + file_name + getSubmitDes(false) + ".txt";
                break;
            case STATUS_FILE_CONTENT_BACK_SHOW:
            case STATUS_BARCODE_DELETE:
            case STATUS_BARCODE_UPDATE:
                path = (String) map.get(TEMPORARY_FILE);
                break;
            case STATUS_OPEN_ONETIME_CREATE_ONETIME:
                calendar = Calendar.getInstance();
                file_name = millionToFormatTime(calendar.getTimeInMillis(), "yyyyMMddHHmmss");
                map.put(FILE_NAME, file_name);
                path = getSDPath() + "/" + getDirectory() + "/" + file_name + ".txt";
                break;
        }
        return path;
    }

    //毫秒转化为指定的日期格式

    public String millionToFormatTime(long millions, String pattern) {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        //前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
        Date dt = new Date(millions);
        return sdf.format(dt);  //得到精确到秒的表示
    }

    //获得根路径
    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = getExternalFilesDir("");
        }
        return sdDir != null ? sdDir.toString() : null;
    }

    private String getDirectory() {
        String s = "";
        int menu_id = (int) map.get(MENU_ID);
        if (menu_id == SCAN_CODE_OFF_IN) {
            s = "离线入库";
        }
        if (menu_id == SCAN_CODE_OFF_OUT) {
            s = "离线出库";
        }
        if (menu_id == SCAN_CODE_OFF_BACK) {
            s = "出库货品回退";
        }
        return s;
    }

    private String getSubmitDes(boolean submit) {
        String s;
        if (submit) {
            s = "已提交";
        } else {
            s = "未提交";
        }
        return s;
    }

    private File getTargetFile(String path) {
        File file = null;
        try {
            file = new File(path);
            makeDir(file.getParentFile());
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    //创建文件目录

    public void makeDir(File dir) {
        if (dir == null) {
            return;
        }
        File parentFile = dir.getParentFile();
        if (parentFile != null) {
            if (!parentFile.exists()) {
                makeDir(dir.getParentFile());
            }
        }
        dir.mkdir();
    }

    private void scanFileContent(File file) {
        String hint = "";
        try {
            if (file != null && file.exists() && file.canRead()) {
                file.getAbsolutePath();
                String path = file.getAbsolutePath();
                FileInputStream inputStream = new FileInputStream(path);
                Scanner scanner = new Scanner(inputStream);
                boolean hasNextLine = scanner.hasNextLine();
                if (hasNextLine) {
                    while (scanner.hasNextLine()) {
                        String s = scanner.nextLine();
                        String barcode = s.trim();
                        if (!barcode.isEmpty()) {
                            tempBarcodeList.add(barcode);
                        }
                    }
                }
                scanner.close();
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            hint = e.getMessage();
        }
        if (!hint.isEmpty()) {
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        removeLoadingAndFriendlyHint(getDirectory() + "\n" + "当天已扫码的数据获取成功");
    }

    //保存条形码集合到指定的File文件

    private void saveBarcodeListToFile(int status, List<String> list, File file) {
        String hint;
        try {
            switch (status) {
                case STATUS_BARCODE_ADD:
                case STATUS_BARCODE_DELETE:
                case STATUS_BARCODE_UPDATE:
                    appendDataToNewFile(list, file, false);
                    break;
                case STATUS_BEFORE_SUBMIT:
                case STATUS_BACK_ICON_PRESS:
                case STATUS_BACK_KEY_PRESS:
                    appendDataToNewFile(list, file, true);
                    break;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            hint = e.getMessage();
            removeLoadingAndFriendlyHint(hint);
        } catch (IOException e) {
            e.printStackTrace();
            hint = e.getMessage();
            removeLoadingAndFriendlyHint(hint);
        } catch (Exception e) {
            e.printStackTrace();
            hint = e.getMessage();
            removeLoadingAndFriendlyHint(hint);
        }
    }

    private void appendDataToNewFile(List<String> list, File file, boolean append) throws Exception {
        int index = 0;
        FileWriter writer;
        if (append) {
            writer = new FileWriter(file.getAbsolutePath(), true);
        } else {
            writer = new FileWriter(file.getAbsolutePath());
        }
        for (String s : list) {
            index++;
            writer.write(s + "\r\n");
            if (index == list.size()) {
                writer.flush();
                writer.close();
            }
        }
        int status = (int) map.get(STATUS);
        if (status == STATUS_BARCODE_ADD) {
            addDataToList();
        }
        if (status == STATUS_BEFORE_SUBMIT) {
            removeLoadingAndFriendlyHint("保存成功");
            mHandler.postDelayed(mRunnable, 0);
        }
        if (status == STATUS_AFTER_SUBMIT) {
            Log.i("TAG", "do nothing");
        }
        if (status == STATUS_BACK_ICON_PRESS) {
            removeLoadingAndFriendlyHint("保存成功");
            finish();
        }
        if (status == STATUS_BACK_KEY_PRESS) {
            removeLoadingAndFriendlyHint("保存成功");
            finish();
        }

        if (status == STATUS_BARCODE_DELETE) {
            removeDataFromList();
        }
        if (status == STATUS_BARCODE_UPDATE) {
            updateDataFromList();
        }
    }

    private String getPathExceptionHint(String path) {
        if (path == null || path.isEmpty()) {
            return "文件路径不存在";
        }
        return "";
    }

    private String getFileExceptionHint(File file) {
        if (file == null) {
            return "文件为空";
        }
        if (!file.exists()) {
            return "文件不存在";
        }
        if (!file.canRead()) {
            return "文件不可读";
        }
        if (!file.canWrite()) {
            return "文件不可写";
        }
        return "";
    }

    private void readFile() {
        String path = getTargetFilePath(STATUS_READ_FILE);
        if (!getPathExceptionHint(path).isEmpty()) {
            removeLoadingAndFriendlyHint(getPathExceptionHint(path));
            return;
        }
        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            removeLoadingAndFriendlyHint(getFileExceptionHint(file));
            return;
        }
        scanFileContent(file);
    }

    /**
     * 扫描一次保存一次
     */
    private void scanOneTimeSaveOneTime() {
        String barcode = (String) map.get(BARCODE);
        if (barcode == null || barcode.isEmpty()) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, "提交内容不存在或者为空" + "\n" + "无需保存");
            });
            return;
        }

        String path = getTargetFilePath(STATUS_BARCODE_ADD);
        if (path == null || path.isEmpty()) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, "找不到目标路径");
                addDataToList();
            });
            return;
        }
        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, getFileExceptionHint(file));
                addDataToList();
            });
            return;
        }
        if (tempBarcodeList.contains(barcode)) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, barcode
                        + "\n"
                        + "文件"
                        + "\n"
                        + file.getName()
                        + "\n"
                        + "已存在"
                        + "\n"
                        + "无需保存");
                addDataToList();
            });
            return;
        }
        tempBarcodeList.add(barcode);
        saveBarcodeListToFile(STATUS_BARCODE_ADD, tempBarcodeList, file);
    }

    private void addDataToList() {
        String barcode = (String) map.get(BARCODE);
        map.put(BARCODE, "");

        if (barcode == null || barcode.isEmpty()) {
            String hint = "条形码不存在或为空";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        if (barcodeResultAdapter == null) {
            String hint = "适配器不存在";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        List<String> list = barcodeResultAdapter.getData();
        if (list.contains(barcode)) {
            String hint = "条形码在当前列表已存在";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        runOnUiThread(() -> {
            barcodeResultAdapter.addData(barcode);
            rv_result.scrollToPosition(barcodeResultAdapter.getData().size() - 1);
            String hint = "保存条码" + "\n" + barcode + "\n" + "成功";
            removeLoadingAndFriendlyHint(hint);
        });
    }

    /**
     * 离线入库
     * 离线出库
     * 出库物品回退
     * 请求网络之前保存
     */
    private void saveBeforeSubmit() {
        List<String> list = barcodeResultAdapter.getData();
        if (list.isEmpty()) {
            removeLoadingAndFriendlyHint("提交内容不存在或者为空" + "\n" + "无需保存");
            return;
        }
        String path = getTargetFilePath(STATUS_BEFORE_SUBMIT);
        if (path == null || path.isEmpty()) {
            removeLoadingAndFriendlyHint("找不到目标路径");
            return;
        }

        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            removeLoadingAndFriendlyHint(getFileExceptionHint(file));
            return;
        }
        saveBarcodeListToFile(STATUS_BEFORE_SUBMIT, list, file);
    }


    /**
     * 离线入库
     * 离线出库
     * 出库物品回退
     * 请求网络成功之后保存
     */
    private void saveAfterSubmit() {
        List<String> list = barcodeResultAdapter.getData();
        if (list.isEmpty()) {
            removeLoadingAndFriendlyHint("提交内容不存在或者为空" + "\n" + "无需保存");
            return;
        }
        String path = getTargetFilePath(STATUS_AFTER_SUBMIT);
        if (path == null || path.isEmpty()) {
            removeLoadingAndFriendlyHint("找不到目标路径");
            return;
        }

        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            removeLoadingAndFriendlyHint(getFileExceptionHint(file));
            return;
        }

        saveBarcodeListToFile(STATUS_AFTER_SUBMIT, list, file);
    }


    /**
     * 界面左上角返回图标点击时
     * 保存并结束当前页面
     */
    private void backIconPress() {
//        List<String> list = barcodeResultAdapter.getData();
//        if (list.isEmpty()) {
//            runOnUiThread(() -> {
//                hideLoading();
//                ToastUtils.showToast(BarcodeListNewActivity.this, "提交内容不存在或者为空" + "\n" + "无需保存");
//                finish();
//            });
//            return;
//        }
//        String path = getTargetFilePath(STATUS_BACK_ICON_PRESS);
//        if (path == null || path.isEmpty()) {
//            runOnUiThread(() -> {
//                hideLoading();
//                ToastUtils.showToast(BarcodeListNewActivity.this, "找不到目标路径");
//                finish();
//            });
//            return;
//        }
//
//        File file = getTargetFile(path);
//        if (!getFileExceptionHint(file).isEmpty()) {
//            runOnUiThread(() -> {
//                hideLoading();
//                ToastUtils.showToast(BarcodeListNewActivity.this, getFileExceptionHint(file));
//                finish();
//            });
//            return;
//        }
//        saveBarcodeListToFile(STATUS_BACK_ICON_PRESS, list, file);

        String path = getTargetFilePath(STATUS_BACK_ICON_PRESS);
        if (path == null || path.isEmpty()) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, "找不到目标路径");
                finish();
            });
            return;
        }

        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, getFileExceptionHint(file));
                finish();
            });
            return;
        }
        List<String> list = barcodeResultAdapter.getData();
        if (list.isEmpty()) {
            file.delete();
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, "提交内容不存在或者为空" + "\n" + "无需保存");
                finish();
            });
            return;
        }
        finish();
    }


    /**
     * Android设备返回键点击时
     * 保存并结束当前页面
     */
    private void backKeyPress() {
//        List<String> list = barcodeResultAdapter.getData();
//        if (list.isEmpty()) {
//            runOnUiThread(() -> {
//                hideLoading();
//                ToastUtils.showToast(BarcodeListNewActivity.this, "提交内容不存在或者为空" + "\n" + "无需保存");
//                finish();
//            });
//            return;
//        }
//        String path = getTargetFilePath(STATUS_BACK_KEY_PRESS);
//        if (path == null || path.isEmpty()) {
//            runOnUiThread(() -> {
//                hideLoading();
//                ToastUtils.showToast(BarcodeListNewActivity.this, "找不到目标路径");
//                finish();
//            });
//            return;
//        }
//
//        File file = getTargetFile(path);
//        if (!getFileExceptionHint(file).isEmpty()) {
//            runOnUiThread(() -> {
//                hideLoading();
//                ToastUtils.showToast(BarcodeListNewActivity.this, getFileExceptionHint(file));
//                finish();
//            });
//            return;
//        }
//
//        saveBarcodeListToFile(STATUS_BACK_KEY_PRESS, list, file);

        String path = getTargetFilePath(STATUS_BACK_ICON_PRESS);
        if (path == null || path.isEmpty()) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, "找不到目标路径");
                finish();
            });
            return;
        }

        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, getFileExceptionHint(file));
                finish();
            });
            return;
        }
        List<String> list = barcodeResultAdapter.getData();
        if (list.isEmpty()) {
            file.delete();
            runOnUiThread(() -> {
                hideLoading();
                ToastUtils.showToast(BarcodeListActivity.this, "提交内容不存在或者为空" + "\n" + "无需保存");
                finish();
            });
            return;
        }
        finish();
    }


    /**
     * 根据日期选择文件
     * 该文件内容的回显
     */
    private void fileContentBackShow() {
        runOnUiThread(() -> {
            barcodeResultAdapter.getData().clear();
            barcodeResultAdapter.notifyDataSetChanged();
        });

        String path = getTargetFilePath(STATUS_FILE_CONTENT_BACK_SHOW);
        File file = getTargetFile(path);
        String hint = getFileContentBackShowHint(path, file);
        if (!hint.isEmpty()) {
            runOnUiThread(() -> ToastUtils.showToast(BarcodeListActivity.this, hint));
            return;
        }
        try {
            readDataFromFile(file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String getFileContentBackShowHint(String path, File file) {
        if (path == null || path.isEmpty()) {
            return "找不到目标路径";
        }
        if (!getFileExceptionHint(file).isEmpty()) {
            return getFileExceptionHint(file);
        }
        return "";
    }

    private void readDataFromFile(String file_name) throws Exception {
        FileInputStream inputStream = new FileInputStream(file_name);
        Scanner scanner = new Scanner(inputStream);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            runOnUiThread(() -> {
                if (!s.trim().isEmpty() && barcodeResultAdapter != null) {
                    List<String> list = barcodeResultAdapter.getData();
                    if (!list.contains(s)) {
                        barcodeResultAdapter.addData(s.trim());
                        rv_result.scrollToPosition(barcodeResultAdapter.getData().size() - 1);
                    }
                }
            });
        }
        tempBarcodeList = barcodeResultAdapter.getData();
        scanner.close();
        inputStream.close();

        removeLoadingAndFriendlyHint("数据展示已完成");
    }


    /**
     * 删除当前列表的某一个条形码
     */
    private void deleteBarcode() {
        String barcode = (String) map.get(BARCODE);
        if (barcode == null || barcode.isEmpty()) {
            removeLoadingAndFriendlyHint("条形码不存在或者为空" + "\n" + "无需保存");
            return;
        }
        tempBarcodeList.remove(barcode);
        String path = getTargetFilePath(STATUS_BARCODE_DELETE);
        if (path == null || path.isEmpty()) {
            removeLoadingAndFriendlyHint("找不到目标路径");
            removeDataFromList();
            return;
        }
        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            removeLoadingAndFriendlyHint(getFileExceptionHint(file));
            removeDataFromList();
            return;
        }
        if (tempBarcodeList == null || tempBarcodeList.isEmpty()) {
            file.delete();
            removeDataFromList();
            return;
        }
        saveBarcodeListToFile(STATUS_BARCODE_DELETE, tempBarcodeList, file);
    }


    private void removeDataFromList() {
        String barcode = (String) map.get(BARCODE);
        map.put(BARCODE, "");
        if (barcode == null || barcode.isEmpty()) {
            String hint = "条形码不存在或为空";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        if (barcodeResultAdapter == null) {
            String hint = "适配器不存在";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        List<String> list = barcodeResultAdapter.getData();
        if (!list.contains(barcode)) {
            String hint = "条形码在列表中不存在" + "\n" + "无需删除";
            removeLoadingAndFriendlyHint(hint);
            return;
        }

        list.remove(barcode);
        runOnUiThread(() -> {
            barcodeResultAdapter.setList(list);
            String hint = "删除条码" + "\n" + barcode + "\n" + "成功";
            removeLoadingAndFriendlyHint(hint);
        });
    }

    /**
     * 更新当前列表的某一个条码
     */
    private void updateBarcode() {
        String barcode = (String) map.get(BARCODE);
        String path = getTargetFilePath(STATUS_BARCODE_UPDATE);
        File file = getTargetFile(path);
        String new_barcode = (String) map.get(BARCODE_NEW);
        String hint = getUpdateBarcodeHint(barcode, path, file, tempBarcodeList, new_barcode);
        if (!hint.isEmpty()) {
            runOnUiThread(() -> ToastUtils.showToast(BarcodeListActivity.this, hint));
            updateDataFromList();
            return;
        }
        tempBarcodeList.remove(barcode);
        tempBarcodeList.add(new_barcode);
        saveBarcodeListToFile(STATUS_BARCODE_UPDATE, tempBarcodeList, file);
    }


    private String getUpdateBarcodeHint(String barcode, String path, File file, List<String> list
            , String new_barcode) {
        if (barcode == null || barcode.isEmpty()) {
            return "条形码不存在或者为空" + "\n" + "无需保存";
        }
        if (path == null || path.isEmpty()) {
            return "找不到目标路径";
        }
        if (!getFileExceptionHint(file).isEmpty()) {
            return getFileExceptionHint(file);
        }
        if (!list.contains(barcode)) {
            return barcode + "\n" + "在文件" + "\n" + file.getName() + "\n" + "不存在" + "\n" + "无需删除";
        }
        if (list.contains(new_barcode)) {
            return new_barcode + "\n" + "在文件" + "\n" + file.getName() + "\n" + "已存在" + "\n" + "无需保存";
        }
        return "";
    }

    private void updateDataFromList() {
        String barcode = (String) map.get(BARCODE);
        String new_barcode = (String) map.get(BARCODE_NEW);
        map.put(BARCODE_NEW, "");
        map.put(BARCODE, "");
        if (barcode == null || barcode.isEmpty()) {
            String hint = "条形码不存在或为空";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        if (new_barcode == null || new_barcode.isEmpty()) {
            String hint = "条形码" + "\n" + barcode + "替换" + "\n" + "不能为空";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        if (barcodeResultAdapter == null) {
            String hint = "适配器不存在";
            removeLoadingAndFriendlyHint(hint);
            return;
        }
        List<String> list = barcodeResultAdapter.getData();
        list.remove(barcode);
        list.add(new_barcode);
        runOnUiThread(() -> {
            barcodeResultAdapter.setList(list);
            String hint = "更新条码" + "\n" + barcode + "为" + new_barcode + "\n" + "成功";
            removeLoadingAndFriendlyHint(hint);
        });
    }

    private void openOneTimeCreateOneTime() {
        String path = getTargetFilePath(STATUS_BARCODE_UPDATE);
        if (!getPathExceptionHint(path).isEmpty()) {
            removeLoadingAndFriendlyHint(getPathExceptionHint(path));
            return;
        }
        File file = getTargetFile(path);
        if (!getFileExceptionHint(file).isEmpty()) {
            removeLoadingAndFriendlyHint(getFileExceptionHint(file));
        }

    }

    @Override
    protected boolean isSave() {
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            saveStatus(STATUS_BACK_KEY_PRESS);
            checkPermissions();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void saveResult() {
        super.saveResult();
//        saveStatus(STATUS_BACK_ICON_PRESS);
//        checkPermissions();
    }

    @Override
    public void initListener() {
        super.initListener();
        tv_submit.setOnClickListener(this);
        edt_result.addTextChangedListener(textWatcher);
        barcodeResultAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.tv_submit) {
//            saveStatus(STATUS_BEFORE_SUBMIT);
//            checkPermissions();
            int menu_id = (int) map.get(MENU_ID);
            submitByMenuId(menu_id);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == 0x1001) {
            if (data == null) {
                return;
            }
            saveStatus(STATUS_FILE_CONTENT_BACK_SHOW);
            String file_name = (String) getSerializableValueByKey(data, "file_name");
            map.put(TEMPORARY_FILE, file_name);
            checkPermissions();
        }
    }

    public Serializable getSerializableValueByKey(Intent mIntent, String key) {
        if (mIntent == null || mIntent.getExtras() == null || key == null || key.isEmpty()) {
            return null;
        }
        Serializable serializable = null;
        Bundle mBundle = mIntent.getExtras();
        try {
            serializable = mBundle.getSerializable(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serializable;
    }

    @Override
    protected void titleRightTextClick() {
        super.titleRightTextClick();
        int menu_id = (int) map.get(MENU_ID);
        skipToFileSelect(menu_id);
    }

    private void skipToFileSelect(int menu_id) {
        if (menu_id != 5 && menu_id != 6 && menu_id != 7) {
            return;
        }
        Class<?> targetClass = getTargetClass(menu_id);
        if (targetClass == null) {
            ToastUtils.showToast(this, "未找到目标路径");
            return;
        }
        Intent mIntent = new Intent(this, targetClass);
        //3 货品盘点  4 货品管咯
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("menu_id", menu_id);
        mIntent.putExtras(mBundle);
        startActivityForResult(mIntent, 1001);
    }

//    private Class<?> getTargetClass(int menu_id) {
//        Class<?> targetClass = null;
//
//        if (menu_id == 5) {
//            targetClass = FileSelectActivity.class;
//        }
//        if (menu_id == 6) {
//            targetClass = FileSelectActivity.class;
//        }
//        if (menu_id == 7) {
//            targetClass = FileSelectActivity.class;
//        }
//        return targetClass;
//    }

    private Class<?> getTargetClass(int menu_id) {
        Class<?> targetClass = null;

        if (menu_id == 5) {
            targetClass = FileSelectNewActivity.class;
        }
        if (menu_id == 6) {
            targetClass = FileSelectNewActivity.class;
        }
        if (menu_id == 7) {
            targetClass = FileSelectNewActivity.class;
        }
        return targetClass;
    }


    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        String barcode = (String) adapter.getItem(position);
        if (view.getId() == R.id.tv_delete) {
            saveStatus(STATUS_BARCODE_DELETE);
            saveBarcode(BARCODE, barcode);
            checkPermissions();
        }
        if (view.getId() == R.id.ll_barcode) {
            saveStatus(STATUS_BARCODE_UPDATE);
            saveBarcode(BARCODE, barcode);
            showModifyDialog(barcode);
        }
    }

    private void showModifyDialog(String barcode) {
        ModifyBarcodeDialog dialog = new ModifyBarcodeDialog();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("barcode", barcode);
        dialog.setArguments(mBundle);
        dialog.setDialogResultListener(result -> {
            saveBarcode(BARCODE_NEW, result);
            checkPermissions();
        });
        dialog.show(getSupportFragmentManager(), "ModifyBarcodeDialog");
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (getSystemDevice().equals("SEUIC")) {
            initReceiver();
            startMyService();
        }
        if (getSystemDevice().equals("Zebra")) {
            initZebra();
        }
        if (isFirst) {
            isFirst = false;
            checkPermissions();
        }
    }

    /**
     * 获取手机设备名
     *
     * @return 手机设备名
     */
    public static String getSystemDevice() {
        return Build.BRAND;
    }

    private void initReceiver() {
        receiver = new ScanReceiver();
        IntentFilter filter = new IntentFilter(ScannerService.ACTION);
        registerReceiver(receiver, filter);
    }

    private void startMyService() {
        Intent intent = new Intent(this, ScannerService.class);
        startService(intent);
    }

    private void initZebra() {
        initZebraListener();
        initZebraEMDKResults();
    }

    private void initZebraListener() {
        emdkListener = new EMDKManager.EMDKListener() {
            @Override
            public void onOpened(EMDKManager emdkManager) {
                emdkManagers = emdkManager;
                // Acquire the barcode manager resources
                initBarcodeManager();
                addConnectionListener();
                initScanner();
            }

            @Override
            public void onClosed() {
                if (emdkManagers != null) {
                    emdkManagers.release();
                    emdkManagers = null;
                }
            }
        };
        scannerDataListener = scanDataCollection -> {
            if ((scanDataCollection != null) && (scanDataCollection.getResult() == ScannerResults.SUCCESS)) {
                ArrayList<ScanDataCollection.ScanData> scanData = scanDataCollection.getScanData();
                for (ScanDataCollection.ScanData data : scanData) {
                    String dataData = data.getData();
                    Log.i("TAG", dataData);
                    saveBarcode(BARCODE, dataData);
                    saveStatus(STATUS_BARCODE_ADD);
                    checkPermissions();
                }
            }
        };

        scannerStatusListener = statusData -> {
            StatusData.ScannerStates state = statusData.getState();
            switch (state) {
                case IDLE:
                    Log.i("TAG", statusData.getFriendlyName() + " is enabled and idle...");
                    // set trigger type
                    if (bSoftTriggerSelected) {
                        scanner.triggerType = com.symbol.emdk.barcode.Scanner.TriggerType.SOFT_ONCE;
                        bSoftTriggerSelected = false;
                    } else {
                        scanner.triggerType = com.symbol.emdk.barcode.Scanner.TriggerType.HARD;
                    }
                    // set decoders
                    if (bDecoderSettingsChanged) {
                        setDecoders();
                        bDecoderSettingsChanged = false;
                    }
                    // submit read
                    if (!scanner.isReadPending() && !bExtScannerDisconnected) {
                        try {
                            scanner.read();
                        } catch (ScannerException e) {
                            Log.i("TAG", e.getMessage());
                        }
                    }
                    break;
                case WAITING:
                    Log.i("TAG", "Scanner is waiting for trigger press...");
                    break;
                case SCANNING:
                    Log.i("TAG", "Scanning...");
                    break;
                case DISABLED:
                    Log.i("TAG", statusData.getFriendlyName() + " is disabled.");
                    break;
                case ERROR:
                    Log.i("TAG", "An error has occurred.");
                    break;
                default:
                    break;
            }
        };
    }

    private void initBarcodeManager() {
        barcodeManager = (BarcodeManager) emdkManagers.getInstance(EMDKManager.FEATURE_TYPE.BARCODE);
    }

    private void addConnectionListener() {
        // Add connection listener
        if (barcodeManager == null) {
            bExtScannerDisconnected = false;
            return;
        }
        barcodeManager.addConnectionListener((scannerInfo, connectionState) -> {
            String status;
            String scannerName;
            String statusExtScanner = connectionState.toString();
            String scannerNameExtScanner = scannerInfo.getFriendlyName();
            ScannerInfo defaultScanner = getScannerInfo();
            if (defaultScanner == null) {
                bExtScannerDisconnected = false;
                status = scannerNameExtScanner + ":" + statusExtScanner;
                Log.i("TAG", status);
                return;
            }
            scannerName = getScannerInfo().getFriendlyName();
            if (scannerName == null || scannerName.isEmpty() ||
                    !scannerName.equalsIgnoreCase(scannerNameExtScanner)) {
                bExtScannerDisconnected = false;
                status = scannerNameExtScanner + ":" + statusExtScanner;
                Log.i("TAG", status);
                return;
            }
            switch (connectionState) {
                case CONNECTED:
                    bSoftTriggerSelected = false;
                    synchronized (lock) {
                        initScanner();
                        bExtScannerDisconnected = false;
                    }
                    break;
                case DISCONNECTED:
                    bExtScannerDisconnected = true;
                    synchronized (lock) {
                        deInitScanner();
                    }
                    break;
            }
            status = scannerNameExtScanner + ":" + statusExtScanner;
            Log.i("TAG", status);
        });
    }

    private ScannerInfo getScannerInfo() {
        if (barcodeManager != null) {
            List<ScannerInfo> deviceList = barcodeManager.getSupportedDevicesInfo();
            if ((deviceList != null) && (deviceList.size() != 0)) {
                for (ScannerInfo scnInfo : deviceList) {
                    if (scnInfo.isDefaultScanner()) {
                        return scnInfo;
                    }
                }
            } else {
                Log.i("TAG", "Failed to get the list of supported scanner devices! Please close and restart the application.");
            }
        }
        return null;
    }


    private void initScanner() {
        if (scanner == null) {
            if (barcodeManager != null) {
                scanner = barcodeManager.getDevice(getScannerInfo());

            }
            if (scanner != null) {
                scanner.addDataListener(scannerDataListener);
                scanner.addStatusListener(scannerStatusListener);
                try {
                    scanner.enable();
                } catch (ScannerException e) {
                    deInitScanner();
                }
            } else {
                Log.i("TAG", "Failed to initialize the scanner device.");
            }
        }
    }

    private void initZebraEMDKResults() {
        EMDKResults results = EMDKManager.getEMDKManager(getApplicationContext(), emdkListener);
        if (results.statusCode != EMDKResults.STATUS_CODE.SUCCESS) {
            Log.i("TAG", "EMDKManager object request failed!");
        }
    }

    private void setDecoders() {
        if (scanner != null) {
            try {
                ScannerConfig config = scanner.getConfig();
                // Set EAN8
                config.decoderParams.ean8.enabled = false;
                // Set EAN13
                config.decoderParams.ean13.enabled = false;
                // Set Code39
                config.decoderParams.code39.enabled = false;
                //Set Code128
                config.decoderParams.code128.enabled = false;
                scanner.setConfig(config);
            } catch (ScannerException e) {
                Log.i("TAG", e.getMessage());
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (getSystemDevice().equals("Zebra")) {
            // The application is in background
            // Release the barcode manager resources
            deInitScanner();
            deInitBarcodeManager();
        }
    }

    private void deInitScanner() {
        if (scanner != null) {
            try {
                scanner.disable();
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                scanner.removeDataListener(scannerDataListener);
                scanner.removeStatusListener(scannerStatusListener);
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                scanner.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            scanner = null;
        }
    }

    private void deInitBarcodeManager() {
        if (emdkManagers != null) {
            emdkManagers.release(EMDKManager.FEATURE_TYPE.BARCODE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver == null) {
            return;
        }
        unregisterReceiver(receiver);
    }

    public class ScanReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            edt_result.append(bundle.getString(ScannerService.BAR_CODE));
        }
    }
}
